

from flask import Blueprint,request,jsonify
from flask_restful import Api,Resource
goods_dp = Blueprint('goods_dp', __name__, url_prefix='/v1')

api = Api(goods_dp)

from toutiao_backend_3.toutiao.model.db_totiao import Channel,db,UserChannel
class ChannelView(Resource):

    def get(self):
        # 获取所有的对象
        goods_list=Channel.query.all()

        goods_all=[]
        for goods in goods_list:
            d={
                'name':goods.name,
                'sequence':goods.sequence,
                'is_visible':goods.is_visible,
                'is_default':goods.is_default,
                'create_time':goods.create_time,
                'update_time':goods.update_time,
            }
            goods_all.append(d)
        return jsonify({'code': 200, 'msg': '文章获取成功',
                        'data': goods_all})
    def post(self):
        # 添加
        args=request.json
        name=args.get('name')
        sequence=args.get('sequence')
        is_visible=args.get('is_visible')
        is_default=args.get('is_default')
        create_time=args.get('create_time')
        update_time=args.get('update_time')
        # all不能返回为空
        if not all([name,sequence,is_visible,is_default,create_time,update_time]):
            return jsonify({'code':400,'msg':'获取失败'})
        goods=Channel(name=name,sequence=sequence,is_visible=is_visible,is_default=is_default,create_time=create_time,update_time=update_time)
        db.session.add(goods)
        # 提交
        db.session.commit()        # 删除一条商品
        goods_info = Channel.query.get(id)

        if not goods_info:
            return jsonify({'code': 400, 'msg': '内容不存在'})
        Channel.query.filter(Channel.id == id).delete()

        db.session.commit()
        return jsonify({'code': 200, 'msg': '删除成功'})
api.add_resource(ChannelView, '/goods')
def UserView():
    user_id=request.form.get('id')
    channel_id=request.form.get('channel_id')
    is_deleted=Channel.query.filter(id=channel_id).first()

    if is_deleted:
        chande=UserChannel.query.filter_by(user_id=user_id,channel_id=channel_id).first()
        if not chande:
            rels=UserChannel(user_id=user_id,channel_id=channel_id,is_deleted=0)
            db.session.add()
            return {'code':'200','msg':'用户关注成功'}
        else:
            chande.is_deleted=0
            db.session.commit()
            return {'code':'200','msg':'用户关注频道'}
    else:
        return {'msg':'频道已删除'}





